<template>
  <div class="dankal-image-upload">
    <!-- 数组 -->
    <div v-if="Array.isArray(list)">
      <draggable v-model="list" @end="dragEnd" group="itxst" animation="300">
        <transition-group>
          <p v-for="(item, index) in list" :key="item">
            <ImagePreview :src="item" :width="width || 100" :height="height || 100" />
            <!-- <img
              class="upload_img"
              :src="imgMapper(item)"
              @click="onPreview(imgMapper(item))"> -->
            <img v-if="edit" class="close" src="@/assets/images/ic_del.png" @click="onDeleted(index)">
          </p>
        </transition-group>
      </draggable>
      <div v-if="edit">
        <img v-if="list.length < limit" @click='onSelected' class="add" src="@/assets/images/ic_add_pic.png">
      </div>
    </div>

    <!-- 字符串 -->
    <div v-else>
      <p v-if="list">
        <ImagePreview :src="list" :width="width || 100" :height="height || 100" />
        <!-- <img
          class="upload_img"
          :src="imgMapper(list)"
          alt=""
          @click="onPreview(imgMapper(list))"> -->
        <img v-if="edit" class="close" src="@/assets/images/ic_del.png" @click="onDeleted(index)">
      </p>
      <div v-if="edit">
        <img v-if="!list" @click='onSelected' class="add" src="@/assets/images/ic_add_pic.png">
      </div>
    </div>

    <input ref="input" type="file" id="file" multiple="multiple" accept="image/*" style="display:none;"
      @change="onFileChanged">

    <!-- 上传提示 -->
    <div v-if="showTip" slot="tip" class="el-upload__tip">
      可上传<b style="color: #f56c6c">{{ limit }}张</b>
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>
    <!-- 自定义提示 -->
    <div v-if="tipsText" slot="tip" class="el-upload__tip">
      {{ tipsText }}
    </div>

    <!-- 预览模态框 -->
    <!-- <el-dialog
      :visible.sync="visible"
      title="预览"
      width="800"
      append-to-body>
      <img class="preview-image" :src="previewImage">
    </el-dialog> -->
  </div>
</template>

<script>
import { imgDomain } from "@/configs/env";
import uploadMixins from "@/mixins/upload"
import draggable from "vuedraggable"

export default {
  name: "DankalImageUpload",
  components: {
    draggable
  },
  data() {
    return {
      list: [],
      toast: "",
      visible: false,
      previewImage: "",
      domain: imgDomain,

      // 裁剪
      cutting: false,
      option: {
        img: "", // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: "jpg", // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        // autoCropWidth: 690, // 默认生成截图框宽度
        // autoCropHeight: 265, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        // fixed: true, // 是否开启截图框宽高固定比例
        // fixedNumber: [7, 5], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: false, // 截图框能否拖动
        original: true, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },

    };
  },

  mixins: [uploadMixins],

  props: {
    width: {
      type: [Number, String],
      default: 100
    },
    height: {
      type: [Number, String],
      default: 100
    },
    value: {
      type: [String, Array],
      required: true
    },
    compress: {
      type: Boolean,
      default: true
    },
    quatity: {
      type: Number,
      default: 0.6
    },
    edit: {
      type: Boolean,
      default: true
    },
    /**
     * qiniu,oss,cos,s3,server(七牛云,阿里云,腾讯云,亚马逊s3,客户服务器)
     */
    channel: {
      type: String,
      default: "oss"
    },
    // 裁剪
    needCropper: {
      type: Boolean,
      default: false
    },
    // 裁剪宽高
    cropperSize: {
      type: Object,
      default: () => ({
        width: 100,
        height: 100
      })
    },
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 3,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    showTip: {
      type: Boolean,
      default: false,
    },
    // 提示文字
    tipsText: {
      type: String,
      default: null,
    },
  },

  watch: {
    value(newVal) {
      if (newVal && newVal[0] === "''") {
        this.list = []
      } else {
        this.list = newVal
      }
    }
  },

  mounted() {
    this.list = this.value;
  },

  methods: {
    // 过滤无域名
    imgMapper(item) {
      if (item && item.indexOf("http") !== 0) {
        return this.domain + item
      }
      return item;
    },
    // 拖动结束
    dragEnd() {
      this.$emit("input", this.list);
    },
    // 图片预览
    onPreview(previewImage) {
      this.previewImage = previewImage
      this.visible = true
    },
    // 点击上传
    onSelected() {
      this.$refs.input.click();
    },

    // 删除
    onDeleted(index) {
      if (Array.isArray(this.list)) {
        this.list.splice(index, 1)
      } else {
        this.list = ""
      }
      this.$emit("input", this.list);
    },

    // 裁剪
    cuttingUpload() {
      this.$refs.cropper.getCropBlob((data) => {
        this.upload(data, this.channel, this.uploadCallback)
        this.cutting = false
      });
    },

    onFileChanged(event) {
      const { files } = event.target;
      if (!files.length) return
      if (files.length > this.limit) {
        this.$Message.error({ content: `只能上传${this.limit}张图片`, duration: 2 })
        return
      }
      // 裁剪
      if (this.needCropper && files.length === 1) {
        // 得到base64字符串
        const reader = new FileReader()
        reader.addEventListener("load", () => {
          this.option.img = reader.result
        });
        reader.readAsDataURL(files[0])
        this.cutting = true
        this.$refs.input.value = ""
      } else {
        // window.showLoading()
        for (let i = 0; i < files.length; i += 1) {
          const file = files[i]

          if (file.size / 1024 / 1024 > 3) {
            this.$message.error(`请上传${this.fileSize}MB以内的图片！`)
            this.$refs.input.value = ""
            // window.hideLoading()
            return
          }
          if (this.compress) {
            this.compressAndUpload(file, this.channel, this.uploadCallback)
          } else {
            this.upload(file, this.channel, this.uploadCallback)
          }
        }
      }
    },
    uploadCallback(key) {
      if (Array.isArray(this.list)) {
        this.list.push(key)
      } else {
        this.list = key
      }
      this.$emit("input", this.list);
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-dialog__wrapper {
    height: 100% !important;
  }
}

.dankal-image-upload {
  >div {
    height: 100px;
  }

  .el-upload__tip {
    height: 30px;
    margin-left: 10px;
  }

  p {
    position: relative;
    width: 100px;
    height: 100px;
    margin: 0 8px;
    float: left;

    .upload_img {
      width: 100px;
      height: 100px;
      object-fit: cover;
      cursor: pointer;
    }

    .close {
      width: 20px;
      height: 20px;
      position: absolute;
      top: -10px;
      right: -10px;
      cursor: pointer;
    }
  }

  .add {
    width: 100px;
    height: 100px;
    margin: 0 8px;
    cursor: pointer;
  }

}
</style>
